<script setup>
import { ref, reactive, onMounted, computed, h } from 'vue'
import { useMainStore } from '../pinia.js'

const mainStore = useMainStore()
const emit = defineEmits(['message'])

// 缓存统计数据
const allCacheStats = ref(null)
const allCacheStatsLoading = ref(false)
const cacheCleanLoading = ref(false)

// 缓存详情模态框
const showCacheDetailsModal = ref(false)
const cacheDetailsData = ref(null)
const cacheDetailsTitle = ref('')

// 智能清理表单
const smartCleanForm = ref({
  cacheType: '',
  maxAge: '',
  maxFiles: '',
  specificFiles: []
})

// 处理记录搜索
const processedSearchForm = ref({
  fileKey: ''
})
const processedSearchLoading = ref(false)
const processedSearchResults = ref([])
const processedSearchStats = ref({
  recordCount: 0,
  totalProcessCount: 0,
  lastUpdated: null
})

// 详情页状态
const showProcessedDetail = ref(false)
const selectedProcessedRecord = ref(null)
const openProcessedDetail = (row) => {
  selectedProcessedRecord.value = row
  showProcessedDetail.value = true
}
const backToSearchList = () => {
  showProcessedDetail.value = false
}

// 删除单条处理记录
const processedDeleteLoading = ref(false)
const deleteSelectedProcessedRecord = async () => {
  try {
    const fileId = selectedProcessedRecord.value?.fileId
    if (!fileId) {
      emit('message', 'error', '缺少fileId，无法删除此记录')
      return
    }
    processedDeleteLoading.value = true
    const response = await fetch(`/api/file/processed/${encodeURIComponent(fileId)}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${mainStore.authToken}`
      }
    })
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    const result = await response.json()
    if (result.success) {
      emit('message', 'success', '删除成功')
      // 从结果列表移除已删除记录
      const deletedId = fileId
      processedSearchResults.value = processedSearchResults.value.filter(r => r.fileId !== deletedId)
      // 重新计算统计
      const recordCount = processedSearchResults.value.length
      const totalProcessCount = processedSearchResults.value.reduce((sum, r) => sum + (typeof r.processCount === 'number' ? r.processCount : 1), 0)
      const lastUpdatedTs = processedSearchResults.value.reduce((max, r) => {
        const t = new Date(r.updatedAt || r.createdAt || 0).getTime()
        return Math.max(max, t)
      }, 0)
      processedSearchStats.value = {
        recordCount,
        totalProcessCount,
        lastUpdated: lastUpdatedTs ? new Date(lastUpdatedTs).toISOString() : null
      }
      showProcessedDetail.value = false
    } else {
      emit('message', 'error', result.message || '删除处理记录失败')
    }
  } catch (error) {
    console.error('删除处理记录错误:', error)
    emit('message', 'error', '删除处理记录失败: ' + error.message)
  } finally {
    processedDeleteLoading.value = false
  }
}

// 缓存类型选项
const cacheTypeOptions = computed(() => {
  if (!allCacheStats.value?.details) return []
  
  return Object.entries(allCacheStats.value.details).map(([type, stats]) => ({
    label: stats.name,
    value: type
  }))
})

// 获取缓存统计信息
const refreshAllCacheStats = async () => {
  try {
    allCacheStatsLoading.value = true
    
    const response = await fetch('/api/file/cache/stats', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${mainStore.authToken}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      allCacheStats.value = result.data
      emit('message', 'success', '缓存统计信息已更新')
    } else {
      emit('message', 'error', result.message || '获取缓存统计信息失败')
    }
  } catch (error) {
    console.error('获取缓存统计信息错误:', error)
    emit('message', 'error', '获取缓存统计信息失败: ' + error.message)
  } finally {
    allCacheStatsLoading.value = false
  }
}

// 智能清理缓存
const smartCleanCache = async () => {
  try {
    cacheCleanLoading.value = true
    
    const cleanOptions = {
      cacheType: smartCleanForm.value.cacheType
    }
    
    // 处理清理选项
    if (smartCleanForm.value.maxAge) {
      cleanOptions.maxAge = smartCleanForm.value.maxAge
    }
    
    if (smartCleanForm.value.maxFiles) {
      cleanOptions.maxFiles = parseInt(smartCleanForm.value.maxFiles)
    }
    
    if (smartCleanForm.value.specificFiles && smartCleanForm.value.specificFiles.length > 0) {
      cleanOptions.specificFiles = smartCleanForm.value.specificFiles
    }
    
    const response = await fetch('/api/file/cache/clean', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${mainStore.authToken}`
      },
      body: JSON.stringify(cleanOptions)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      emit('message', 'success', result.message)
      // 刷新统计信息
      await refreshAllCacheStats()
      // 重置表单
      resetSmartCleanForm()
    } else {
      emit('message', 'error', result.message || '清理缓存失败')
    }
  } catch (error) {
    console.error('清理缓存错误:', error)
    emit('message', 'error', '清理缓存失败: ' + error.message)
  } finally {
    cacheCleanLoading.value = false
  }
}

// 清理特定类型的缓存
const clearCacheType = async (cacheType) => {
  try {
    cacheCleanLoading.value = true
    
    const response = await fetch('/api/file/cache/clean', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${mainStore.authToken}`
      },
      body: JSON.stringify({ cacheType })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      emit('message', 'success', result.message)
      await refreshAllCacheStats()
    } else {
      emit('message', 'error', result.message || '清理缓存失败')
    }
  } catch (error) {
    console.error('清理缓存错误:', error)
    emit('message', 'error', '清理缓存失败: ' + error.message)
  } finally {
    cacheCleanLoading.value = false
  }
}

// 清空所有缓存
const clearAllCacheTypes = async () => {
  try {
    cacheCleanLoading.value = true
    
    const response = await fetch('/api/file/cache/clear-all', {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${mainStore.authToken}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      emit('message', 'success', result.message)
      await refreshAllCacheStats()
    } else {
      emit('message', 'error', result.message || '清理所有缓存失败')
    }
  } catch (error) {
    console.error('清理所有缓存错误:', error)
    emit('message', 'error', '清理所有缓存失败: ' + error.message)
  } finally {
    cacheCleanLoading.value = false
  }
}

// 查看缓存详情
const viewCacheDetails = async (cacheType) => {
  try {
    // 获取缓存详情数据
    const response = await fetch(`/api/file/cache/details/${cacheType}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${mainStore.authToken}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      // 设置详情数据并打开模态框
      cacheDetailsData.value = result.data
      cacheDetailsTitle.value = `${result.data.name} 详细信息`
      showCacheDetailsModal.value = true
    } else {
      emit('message', 'error', result.message || '获取缓存详情失败')
    }
  } catch (error) {
    console.error('获取缓存详情错误:', error)
    emit('message', 'error', '获取缓存详情失败: ' + error.message)
  }
}

// 重置智能清理表单
const resetSmartCleanForm = () => {
  smartCleanForm.value = {
    cacheType: '',
    maxAge: '',
    maxFiles: '',
    specificFiles: []
  }
}

// 搜索处理记录（通过fileKey）
const searchProcessedRecords = async () => {
  try {
    const key = processedSearchForm.value.fileKey?.trim()
    if (!key) {
      emit('message', 'warning', '请输入要搜索的fileKey')
      return
    }
    processedSearchLoading.value = true
    processedSearchResults.value = []
    processedSearchStats.value = { recordCount: 0, totalProcessCount: 0, lastUpdated: null }

    const url = `/api/file/processed/search?fileKey=${encodeURIComponent(key)}`
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${mainStore.authToken}`
      }
    })
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    const result = await response.json()
    if (result.success) {
      processedSearchResults.value = result.data?.records || []
      processedSearchStats.value = result.data?.stats || { recordCount: 0, totalProcessCount: 0, lastUpdated: null }
      emit('message', 'success', `搜索完成：找到 ${processedSearchStats.value.recordCount} 条记录`)
    } else {
      emit('message', 'error', result.message || '搜索处理记录失败')
    }
  } catch (error) {
    console.error('搜索处理记录错误:', error)
    emit('message', 'error', '搜索处理记录失败: ' + error.message)
  } finally {
    processedSearchLoading.value = false
  }
}

const resetProcessedSearch = () => {
  processedSearchForm.value.fileKey = ''
  processedSearchResults.value = []
  processedSearchStats.value = { recordCount: 0, totalProcessCount: 0, lastUpdated: null }
}

const clearAllProcessedRecords = async () => {
  try {
    processedSearchLoading.value = true
    const response = await fetch('/api/file/processed/clear-all', {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${mainStore.authToken}`
      }
    })
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    const result = await response.json()
    if (result.success) {
      processedSearchResults.value = []
      processedSearchStats.value = { recordCount: 0, totalProcessCount: 0, lastUpdated: null }
      emit('message', 'success', result.message || '已清空所有处理记录')
    } else {
      emit('message', 'error', result.message || '清空处理记录失败')
    }
  } catch (error) {
    console.error('清空处理记录错误:', error)
    emit('message', 'error', '清空处理记录失败: ' + error.message)
  } finally {
    processedSearchLoading.value = false
  }
}

// 获取文件选项
const getFileOptionsForType = (cacheType) => {
  if (!allCacheStats.value?.details[cacheType]) return []
  
  return allCacheStats.value.details[cacheType].files.map(file => ({
    label: file.orderNo ? `${file.orderNo} (${file.filename})` : file.filename,
    value: file.filename
  }))
}

// 获取缓存类型的显示名称
const getCacheTypeName = (type) => {
  if (allCacheStats.value?.details[type]) {
    return allCacheStats.value.details[type].name
  }
  const names = {
    'trf-results': 'TRF结果',
    'uploaded-files': '上传文件',
    'processed-files': '处理结果',
    'temp-files': '临时文件'
  }
  return names[type] || type
}

// 获取缓存类型的颜色
const getCacheTypeColor = (type) => {
  const colors = {
    'trf-results': 'success',
    'uploaded-files': 'info',
    'processed-files': 'warning',
    'temp-files': 'error'
  }
  return colors[type] || 'default'
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  refreshAllCacheStats()
})
</script>

<template>
  <div class="cache-management">
    <n-card title="系统缓存管理" :bordered="false" class="management-card">
      <template #header-extra>
        <n-space>
          <n-tag type="warning" size="small">管理员功能</n-tag>
          <n-button size="small" @click="refreshAllCacheStats" :loading="allCacheStatsLoading">
            刷新统计
          </n-button>
        </n-space>
      </template>
      
      <n-tabs type="line" animated>
        <!-- 缓存概览 -->
        <n-tab-pane name="overview" tab="缓存概览">
          <n-spin :show="allCacheStatsLoading">
            <div v-if="allCacheStats">
              <!-- 总体统计 -->
              <n-card title="总体统计" size="small" style="margin-bottom: 16px;" :bordered="false">
                <n-descriptions :column="3" bordered>
                  <n-descriptions-item label="总文件数">
                    <n-tag type="info">{{ allCacheStats.summary.totalFiles }} 个</n-tag>
                  </n-descriptions-item>
                  <n-descriptions-item label="总占用空间">
                    <n-tag type="warning">{{ (allCacheStats.summary.totalSize / 1024 / 1024).toFixed(2) }} MB</n-tag>
                  </n-descriptions-item>
                  <n-descriptions-item label="缓存类型">
                    <n-tag type="success">{{ allCacheStats.summary.cacheTypes }} 种</n-tag>
                  </n-descriptions-item>
                </n-descriptions>
              </n-card>
              
              <!-- 各类型缓存详情 -->
              <n-grid :cols="2" :x-gap="16" :y-gap="16">
                <n-gi v-for="(stats, type) in allCacheStats.details" :key="type">
                  <n-card :title="stats.name" size="small" :bordered="false">
                    <template #header-extra>
                      <n-tag size="small" :type="getCacheTypeColor(type)">{{ type.toUpperCase() }}</n-tag>
                    </template>
                    
                    <n-space vertical>
                      <n-text depth="3" style="font-size: 12px;">{{ stats.description }}</n-text>
                      
                      <n-descriptions :column="1" size="small">
                        <n-descriptions-item label="文件数量">
                          {{ stats.totalFiles }} 个
                        </n-descriptions-item>
                        <n-descriptions-item label="占用空间">
                          {{ (stats.totalSize / 1024 / 1024).toFixed(2) }} MB
                        </n-descriptions-item>
                      </n-descriptions>
                      
                      <n-space>
                        <n-button size="small" @click="viewCacheDetails(type)">
                          查看详情
                        </n-button>
                        <n-popconfirm @positive-click="clearCacheType(type)">
                          <template #trigger>
                            <n-button size="small" type="error" :disabled="stats.totalFiles === 0">
                              清空
                            </n-button>
                          </template>
                          确定要清空所有{{ stats.name }}吗？此操作不可恢复。
                        </n-popconfirm>
                      </n-space>
                    </n-space>
                  </n-card>
                </n-gi>
              </n-grid>
              
              <n-divider />
              
              <n-space justify="center">
                <n-button @click="refreshAllCacheStats" :loading="allCacheStatsLoading">
                  刷新统计
                </n-button>
                <n-popconfirm @positive-click="clearAllCacheTypes">
                  <template #trigger>
                    <n-button type="error" :disabled="allCacheStats.summary.totalFiles === 0">
                      清空所有缓存
                    </n-button>
                  </template>
                  确定要清空所有类型的缓存文件吗？此操作不可恢复。
                </n-popconfirm>
              </n-space>
            </div>
            <div v-else>
              <n-empty description="暂无缓存统计数据" />
            </div>
          </n-spin>
        </n-tab-pane>

        <!-- 智能清理 -->
        <n-tab-pane name="smart-clean" tab="智能清理">
          <n-form :model="smartCleanForm" label-placement="left" label-width="120px">
            <n-form-item label="缓存类型">
              <n-select
                v-model:value="smartCleanForm.cacheType"
                placeholder="选择要清理的缓存类型"
                :options="cacheTypeOptions"
              />
            </n-form-item>
            
            <n-form-item label="按时间清理">
              <n-input 
                v-model:value="smartCleanForm.maxAge" 
                placeholder="例如: 7d (7天前), 24h (24小时前)"
              >
                <template #suffix>
                  <n-text depth="3" style="font-size: 12px;">支持: d(天), h(小时)</n-text>
                </template>
              </n-input>
            </n-form-item>
            
            <n-form-item label="按数量清理">
              <n-input-number 
                v-model:value="smartCleanForm.maxFiles" 
                placeholder="保留最新的N个文件"
                :min="0"
                style="width: 100%;"
              />
            </n-form-item>
            
            <n-form-item label="指定文件清理" v-if="smartCleanForm.cacheType">
              <n-select
                v-model:value="smartCleanForm.specificFiles"
                multiple
                filterable
                tag
                placeholder="选择要删除的文件"
                :options="getFileOptionsForType(smartCleanForm.cacheType)"
              />
            </n-form-item>
            
            <n-divider />
            
            <n-space>
              <n-button 
                type="primary" 
                @click="smartCleanCache" 
                :loading="cacheCleanLoading"
                :disabled="!smartCleanForm.cacheType || (!smartCleanForm.maxAge && !smartCleanForm.maxFiles && (!smartCleanForm.specificFiles || smartCleanForm.specificFiles.length === 0))"
              >
                智能清理
              </n-button>
              <n-button @click="resetSmartCleanForm">
                重置表单
              </n-button>
            </n-space>
          </n-form>
        </n-tab-pane>

        <!-- 处理记录搜索 -->
        <n-tab-pane name="processed-search" tab="处理记录搜索">
          <n-card size="small" title="按 fileKey 搜索已处理记录" style="margin-bottom: 16px;">
            <n-form :model="processedSearchForm" label-placement="left" label-width="120px">
              <n-form-item label="fileKey">
                <n-input v-model:value="processedSearchForm.fileKey" placeholder="输入fileKey，如订单号或询价单号" />
              </n-form-item>
              <n-space>
                <n-button type="primary" @click="searchProcessedRecords" :loading="processedSearchLoading">搜索</n-button>
                <n-button @click="resetProcessedSearch" :disabled="processedSearchLoading">清空</n-button>
                <n-popconfirm @positive-click="clearAllProcessedRecords" positive-text="清空" negative-text="取消">
                  <template #trigger>
                    <n-button type="error" :loading="processedSearchLoading">清空所有处理记录</n-button>
                  </template>
                  确定要清空所有处理记录吗？此操作仅删除记录，不会删除已生成的PDF文件。
                </n-popconfirm>
              </n-space>
            </n-form>
          </n-card>

          <n-spin :show="processedSearchLoading">
            <template v-if="!showProcessedDetail">
              <div v-if="processedSearchResults && processedSearchResults.length > 0">
                <n-card size="small" title="搜索结果" :bordered="false">
                  <n-descriptions :column="3" bordered style="margin-bottom: 12px;">
                    <n-descriptions-item label="记录条数">{{ processedSearchStats.recordCount }}</n-descriptions-item>
                    <n-descriptions-item label="总处理次数">{{ processedSearchStats.totalProcessCount }}</n-descriptions-item>
                    <n-descriptions-item label="最后更新">{{ processedSearchStats.lastUpdated ? formatDate(processedSearchStats.lastUpdated) : 'N/A' }}</n-descriptions-item>
                  </n-descriptions>

                  <n-data-table
                    :columns="[
                      { title: 'fileKey', key: 'fileKey' },
                      { title: '原始文件名', key: 'originalName', ellipsis: { tooltip: true } },
                      { title: '处理后文件', key: 'processedFileName' },
                      { title: '处理次数', key: 'processCount' },
                      { title: '创建时间', key: 'createdAt', render: (row) => formatDate(row.createdAt) },
                      { title: '更新时间', key: 'updatedAt', render: (row) => formatDate(row.updatedAt) },
                      { title: '操作', key: 'actions', render: (row) => h('div', [
                        h(
                          'a',
                          {
                            href: row.downloadUrl,
                            target: '_blank',
                            style: 'margin-right: 12px;'
                          },
                          '下载PDF'
                        ),
                        h(
                          'a',
                          {
                            href: 'javascript:void(0);',
                            onClick: () => openProcessedDetail(row)
                          },
                          '详情'
                        )
                      ]) }
                    ]"
                    :data="processedSearchResults"
                    :pagination="{ pageSize: 10 }"
                    :scroll-x="900"
                  />
                </n-card>
              </div>
              <div v-else>
                <n-empty description="没有匹配的处理记录" />
              </div>
            </template>

            <template v-else>
              <n-card size="small" :title="`单号 ${selectedProcessedRecord?.fileKey} 详情`">
                <template #header-extra>
                  <n-space>
                    <n-button size="small" @click="backToSearchList">返回搜索结果</n-button>
                    <n-popconfirm @positive-click="deleteSelectedProcessedRecord" positive-text="删除" negative-text="取消">
                      <template #trigger>
                        <n-button size="small" type="error" :disabled="!selectedProcessedRecord?.fileId" :loading="processedDeleteLoading">
                          删除此记录
                        </n-button>
                      </template>
                      确认删除此处理记录？
                    </n-popconfirm>
                  </n-space>
                </template>

                <n-descriptions :column="3" bordered style="margin-bottom: 12px;">
                  <n-descriptions-item label="fileKey">{{ selectedProcessedRecord?.fileKey }}</n-descriptions-item>
                  <n-descriptions-item label="原始文件名">{{ selectedProcessedRecord?.originalName }}</n-descriptions-item>
                  <n-descriptions-item label="处理后文件">{{ selectedProcessedRecord?.processedFileName }}</n-descriptions-item>
                  <n-descriptions-item label="处理次数">{{ selectedProcessedRecord?.processCount }}</n-descriptions-item>
                  <n-descriptions-item label="创建时间">{{ selectedProcessedRecord?.createdAt ? formatDate(selectedProcessedRecord.createdAt) : 'N/A' }}</n-descriptions-item>
                  <n-descriptions-item label="更新时间">{{ selectedProcessedRecord?.updatedAt ? formatDate(selectedProcessedRecord.updatedAt) : 'N/A' }}</n-descriptions-item>
                  <n-descriptions-item label="下载链接">
                    <a :href="selectedProcessedRecord?.downloadUrl" target="_blank">下载PDF</a>
                  </n-descriptions-item>
                  <n-descriptions-item label="处理文件路径" :span="2">{{ selectedProcessedRecord?.processedFilePath }}</n-descriptions-item>
                </n-descriptions>

                <n-tabs type="line" animated>
                  <n-tab-pane name="record-json" tab="记录JSON">
                    <n-scrollbar style="max-height: 600px;">
                      <pre style="white-space: pre-wrap; font-family: monospace; font-size: 13px; line-height: 1.5;">{{ JSON.stringify(selectedProcessedRecord, null, 2) }}</pre>
                    </n-scrollbar>
                  </n-tab-pane>

                  <n-tab-pane name="dff-info" tab="DFF信息">
                    <n-scrollbar style="max-height: 600px;">
                      <pre style="white-space: pre-wrap; font-family: monospace; font-size: 13px; line-height: 1.5;">{{ JSON.stringify(selectedProcessedRecord?.dffInfo, null, 2) }}</pre>
                    </n-scrollbar>
                  </n-tab-pane>

                  <n-tab-pane name="pbi-stats" tab="PBI统计">
                    <n-scrollbar style="max-height: 600px;">
                      <pre style="white-space: pre-wrap; font-family: monospace; font-size: 13px; line-height: 1.5;">{{ JSON.stringify(selectedProcessedRecord?.powerBiStats, null, 2) }}</pre>
                    </n-scrollbar>
                  </n-tab-pane>
                </n-tabs>
              </n-card>
            </template>
          </n-spin>
        </n-tab-pane>
      </n-tabs>
    </n-card>
    
    <!-- 缓存详情模态框 -->
    <n-modal 
      v-model:show="showCacheDetailsModal" 
      preset="card" 
      :title="cacheDetailsTitle"
      style="width: 80%; max-width: 1000px;"
    >
      <div v-if="cacheDetailsData">
        <n-descriptions :column="2" bordered style="margin-bottom: 16px;">
          <n-descriptions-item label="缓存类型">
            <n-tag :type="getCacheTypeColor(cacheDetailsData.type)">
              {{ cacheDetailsData.name }}
            </n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="文件数量">
            {{ cacheDetailsData.totalFiles }} 个
          </n-descriptions-item>
          <n-descriptions-item label="总大小">
            {{ formatFileSize(cacheDetailsData.totalSize) }}
          </n-descriptions-item>
          <n-descriptions-item label="最后更新">
            {{ cacheDetailsData.lastModified ? formatDate(cacheDetailsData.lastModified) : 'N/A' }}
          </n-descriptions-item>
        </n-descriptions>
        
        <n-data-table
          :columns="[
            { title: '文件名', key: 'filename', ellipsis: { tooltip: true } },
            { title: '大小', key: 'size', render: (row) => formatFileSize(row.size) },
            { title: '创建时间', key: 'createdAt', render: (row) => formatDate(row.createdAt) },
            { title: '最后访问', key: 'accessedAt', render: (row) => formatDate(row.accessedAt) }
          ]"
          :data="cacheDetailsData.files || []"
          :pagination="{ pageSize: 10 }"
          :scroll-x="600"
        />
      </div>
      
      <template #footer>
        <n-space justify="end">
          <n-button @click="showCacheDetailsModal = false">关闭</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<style lang="stylus" scoped>
.cache-management
  .management-card
    min-height: 600px
    
  .n-statistic
    text-align: center
</style>
